import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { CreateTokenDto } from './dto/create-token.dto';
import { AuthPostDto } from './dto/auth.post.dto';
import { LocalStorageService } from '../common/local-storage/local-storage.service';
import { TOKEN } from '../common/local-storage/local-storage.namespace';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  })
};

@Injectable({
  providedIn: 'root'
})
export class LoginService {
  private token: string;

  constructor(
    private http: HttpClient,
    private localStorageService: LocalStorageService
  ) {
    this.token = localStorageService.get(TOKEN);
  }

  getToken() {
    return this.token;
  }

  setToken(token: string) {
    this.token = token;
    this.localStorageService.set(TOKEN, token);
  }

  login(createTokenDto: CreateTokenDto) {
    return this.http
      .post<AuthPostDto>('api/auth', createTokenDto, httpOptions)
      .pipe();
  }
}
